package com.study.my.config;

import com.study.my.entity.User;
import com.study.my.util.RedisObjceSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    /*@Bean
    public JedisConnectionFactory redisConnectionFactory() {
        return new JedisConnectionFactory();
    }*/

    /**
     * 需要注意几点：
        在添加RedisConfig配置时，
        因为连接redis需要RedisConnection和RedisConnectionFactory，
        RedisConnection是通过RedisConnectionFactory进行创建若注入JedisConnnectionFactory，
        如果我们Redis设置了密码，在重新注入RedisConnectionFactory(如上注释代码)，就会报错如下：
        Caused by: redis.clients.jedis.exceptions.JedisDataException: NOAUTH Authentication required.
     */

    @Bean
    public RedisTemplate<String,User> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String,User> template = new RedisTemplate<String,User>();
        template.setConnectionFactory(factory);
        template.afterPropertiesSet();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new RedisObjceSerializer());
        return template;

    }
}
